package util

import (
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

func GetPagination(c *gin.Context) map[string]interface{} {
	pagination := make(map[string]interface{})
	page := c.DefaultQuery("page", "1")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		pageInt = 1
	}
	pageSize := c.DefaultQuery("page_size", "10")

	pageSizeInt, err := strconv.Atoi(pageSize)
	if err != nil {
		pageSizeInt = 10
	}
	pagination["pageSize"] = pageSizeInt

	pagination["page"] = pageInt
	current := c.DefaultQuery("current", "1")
	currentInt, err := strconv.Atoi(current)
	if err != nil {
		currentInt = 1
	}
	pagination["current"] = currentInt

	sorts := c.DefaultQuery("sorts", "")
	if sorts != "" {
		pagination["sorts"] = GetSort(sorts)
	}

	return pagination
}

func GetSort(sorts string) []string {
	sortsArr := strings.Split(sorts, ",")
	list := []string{}
	for i := 0; i < len(sortsArr); i++ {
		if sortsArr[i][0:1] == "-" {
			list = append(list, sortsArr[i][1:]+" desc")
		} else {
			list = append(list, sortsArr[i]+" asc")
		}
	}

	return list
}
